#include <string> 
#include <list>
#include <string.h>
#include <stdio.h>

#include "format.h"

format::format(const std::string &_init):
    m_str(new std::string(_init)),
    m_pnum(1)
{
}
	
format::format(const format &_cp)
{
    m_str = _cp.m_str;
    m_pnum = _cp.m_pnum + 1;
}
    
	
std::string format::str()
{
    return *m_str;
}

format format::arg(const std::string &_par)
{
	    
    if (m_str.get() != NULL)
    {
	replace_perc(*m_str, m_pnum, _par);
    }
	    
    format s(*this);
	    
    return s ;
}

format format::arg(const std::string &_arg1,const std::string &_arg2)
{
    if (m_str.get() != NULL)
    {
	replace_perc(*m_str, m_pnum, _arg1);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg2);
    }
	    
    format s(*this);
	    
    return s ;
}

format format::arg(const std::string &_arg1, const std::string &_arg2, const std::string &_arg3)
{
    if (m_str.get() != NULL)
    {
	replace_perc(*m_str, m_pnum, _arg1);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg2);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg3);
    }
	    
    format s(*this);
	    
    return s ;
}

format format::arg(const std::string &_arg1, const std::string &_arg2, const std::string &_arg3, const std::string &_arg4)
{
    if (m_str.get() != NULL)
    {
	replace_perc(*m_str, m_pnum, _arg1);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg2);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg3);
	m_pnum++;
	replace_perc(*m_str, m_pnum, _arg4);
    }
	    
    format s(*this);
	    
    return s ;

}

format format::num(int _arg)
{
    char buffer[50];
    
    snprintf(buffer, sizeof(buffer), "%d", _arg);
    
    return arg(buffer);
}

format format::time(time_t _arg)
{
    char buffer[50];
    
    snprintf(buffer, sizeof(buffer), "%ld", _arg);
    
    return arg(buffer);
}

	
void format::replace_perc(std::string &_buffer, int _num, const std::string &_str)
{
    char buffer[100];

    memset(buffer, 0, sizeof(buffer));

    std::string::size_type len = snprintf(buffer, sizeof(buffer)-1, "%%%d", _num);

    std::string::size_type pos = 0;

    while ( (pos = _buffer.find(buffer, pos )) != std::string::npos)
    {
  	  if (atoi(_buffer.c_str() + pos + 1) == _num)
  	  {
		_buffer.replace(pos, len , _str);
		pos += len;
	  }
	  else
	  {
		pos++;
	  }

    }
}

